<?php
/**
 * Created by PhpStorm.
 * User: lz
 * Date: 2017/9/29
 * Time: 10:51
 */

namespace app\common\service;

use app\common\service\weixin\TemplateService;
use app\models\market\MarketQrcode;
use app\models\market\QrcodeScanHistory;
use app\models\member\Member;


class ListService
{
    /**绑定 微信昵称 头像
     * @param $item
     * @return bool
     */
    public static function handleMemberAvatar($data = [])
    {
//        $data = @json_decode($item['data'], true);

        if (!isset($data['member_id']) || !isset($data['avatar_url'])) {
            return false;
        }


        if (!$data['member_id'] || !$data['avatar_url']) {
            return false;
        }

        $member_info = Member::findOne(['id' => $data['member_id']]);
        if (!$member_info) {
            return false;
        }

        $ret = UploadService::uploadByUrl($data['avatar_url'], "avatar");
        if ($ret) {
            $member_info->avatar = $ret['path'];
            $member_info->update(0);
        }
        return true;
    }

    /**
     * 绑定微信相关通知
     */
    public static function handleBind($data = [])
    {
//        $data = @json_decode($item['data'], true);

        if (!isset($data['member_id']) || !isset($data['openid'])) {
            return false;
        }

        if (!$data['member_id'] || !$data['openid']) {
            return false;
        }

        $member_info = Member::findOne(['id' => $data['member_id']]);

        if (!$member_info) {
            return false;
        }

        $scan_info = QrcodeScanHistory::find()->where(['openid' => $data['openid']])->one();
        if (!$scan_info) {
            return false;
        }

        $qrcode_info = MarketQrcode::find()->where(['id' => $scan_info['qrcode_id']])->one();
        if (!$qrcode_info) {
            return false;
        }

        $qrcode_info->total_reg_count += 1;
        $qrcode_info->update(0);

        TemplateService::bindNotice($data['member_id']);
        return true;
    }

    /**
     * 支付完成相关通知
     */
    public static function handlePay($data = [])
    {

        if (!isset($data['member_id']) || !isset($data['pay_order_id'])) {
            return false;
        }

        if (!$data['member_id'] || !$data['pay_order_id']) {
            return false;
        }

        TemplateService::payNotice($data['pay_order_id']);

        return true;
    }

    /**
     * 确认发货通知
     */
    public static function handleExpress($data = [])
    {

        if (!isset($data['member_id']) || !isset($data['pay_order_id'])) {
            return false;
        }

        if (!$data['member_id'] || !$data['pay_order_id']) {
            return false;
        }

        $ret = TemplateService::expressNotice($data['pay_order_id']);

        return $ret;
    }
}